package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class VideServiceImpl implements VideoService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;

    @Override
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件查询对象(userid)
        Query query = new Query(Criteria.where("userId").is(userId));

        //2.查询推荐视频表获取总条数
        long count = mongoTemplate.count(query, RecommendVideo.class);

        //3.追加条件(分页排序)
        query.with(Sort.by(Sort.Order.desc("date")))
                .skip((pageNum-1)*pageSize).limit(pageSize);

        //4.查询推荐给视频list
        List<RecommendVideo> recommendVideos = mongoTemplate.find(query, RecommendVideo.class);

        //5.遍历推荐视频list,获取视频id,去视频表查找具体的视频详情,将每个视频详情放入预先声明的videoList中
        List<Video> videoList = new ArrayList<>();
        if (CollUtil.isNotEmpty(recommendVideos)) {
            recommendVideos.forEach(recommendVideo -> {
                Video video = mongoTemplate.findById(recommendVideo.getVideoId(), Video.class);
                videoList.add(video);
            });
        }

        //6.封装PageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,videoList);
    }

    @Override
    public void save(Video video) {
        //1.给video设置vid,为推荐系统使用
        video.setVid(redisIdService.getNextId(ConstantUtil.VIDEO_ID));

        //2.保存到video表中
        mongoTemplate.save(video);

        //3.为了方便查看自己的视频,建议把视频推荐给自己
        RecommendVideo recommendVideo = new RecommendVideo();
        //可以使用系统时间,也可以使用视频发布时间
        recommendVideo.setDate(System.currentTimeMillis());
        recommendVideo.setVid(video.getVid());
        recommendVideo.setUserId(video.getUserId());
        recommendVideo.setVideoId(video.getId());
        recommendVideo.setScore(99.99D);

        mongoTemplate.save(recommendVideo);
    }
}
